using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;

namespace ScrewTurnHelper.Syntax
{
	public abstract class SourceFormat
	{
		/// <summary/>
		protected SourceFormat()
		{
			_tabSpaces = 4;
			_lineNumbers = false;
			_alternate = false;
		}

		private byte _tabSpaces;

		/// <summary>
		/// Gets or sets the tabs width.
		/// </summary>
		/// <value>The number of space characters to substitute for tab 
		/// characters. The default is <b>4</b>, unless overridden is a 
		/// derived class.</value>
		public byte TabSpaces
		{
			get { return _tabSpaces; }
			set { _tabSpaces = value; }
		}

		private bool _lineNumbers;

		/// <summary>
		/// Enables or disables line numbers in output.
		/// </summary>
		/// <value>When <b>true</b>, line numbers are generated. 
		/// The default is <b>false</b>.</value>
		public bool LineNumbers
		{
			get { return _lineNumbers; }
			set { _lineNumbers = value; }
		}

		private bool _alternate;

		/// <summary>
		/// Enables or disables alternating line background.
		/// </summary>
		/// <value>When <b>true</b>, lines background is alternated. 
		/// The default is <b>false</b>.</value>
		public bool Alternate
		{
			get { return _alternate; }
			set { _alternate = value; }
		}


		/// <overloads>Transform source code to HTML 4.01.</overloads>
		/// 
		/// <summary>
		/// Transforms a source code stream to HTML 4.01.
		/// </summary>
		/// <param name="source">Source code stream.</param>
		/// <returns>A string containing the HTML formatted code.</returns>
		public string FormatCode(Stream source)
		{
			var reader = new StreamReader(source);
			string s = reader.ReadToEnd();
			reader.Close();
			return FormatCode(s, _lineNumbers, _alternate, false);
		}

		/// <summary>
		/// Transforms a source code string to HTML 4.01.
		/// </summary>
		/// <returns>A string containing the HTML formatted code.</returns>
		public string FormatCode(string source)
		{
			return FormatCode(source, _lineNumbers, _alternate, false);
		}

		/// <summary>
		/// Allows formatting a part of the code in a different language,
		/// for example a JavaScript block inside an HTML file.
		/// </summary>
		public string FormatSubCode(string source)
		{
			return FormatCode(source, false, false, true);
		}

		/// <summary>
		/// Gets the CSS stylesheet as a stream.
		/// </summary>
		/// <returns>A text <see cref="Stream"/> of the CSS definitions.</returns>
		public static Stream GetCssStream()
		{
			var ress = Assembly.GetExecutingAssembly().GetManifestResourceNames();
			var result = Assembly.GetExecutingAssembly().GetManifestResourceStream(
				"ScrewTurnHelper.Syntax.csharp.css");
			return result;
		}

		/// <summary>
		/// Gets the CSS stylesheet as a string.
		/// </summary>
		/// <returns>A string containing the CSS definitions.</returns>
		public static string GetCssString()
		{
			StreamReader reader = new StreamReader(GetCssStream());
			return reader.ReadToEnd();
		}

		private Regex codeRegex;

		/// <summary>
		/// The regular expression used to capture language tokens.
		/// </summary>
		protected Regex CodeRegex
		{
			get { return codeRegex; }
			set { codeRegex = value; }
		}

		/// <summary>
		/// Called to evaluate the HTML fragment corresponding to each 
		/// matching token in the code.
		/// </summary>
		/// <param name="match">The <see cref="Match"/> resulting from a 
		/// single regular expression match.</param>
		/// <returns>A string containing the HTML code fragment.</returns>
		protected abstract string MatchEval(Match match);

		//does the formatting job
		private string FormatCode(string source, bool lineNumbers, bool alternate, bool subCode)
		{
			source = source.Replace("\n\r", "\n");
			source = source.Replace("\r\n", "\n");
			source = source.Replace("\r", "\n");

			//replace special characters
			var sb = new StringBuilder(source);

			if(!subCode)
			{
				sb.Replace("&", "&amp;");
				sb.Replace("<", "&lt;");
				sb.Replace(">", "&gt;");
				sb.Replace("\t", string.Empty.PadRight(_tabSpaces));
			}

			//color the code
			source = codeRegex.Replace(NormalizeTabs(sb.ToString()), new MatchEvaluator(MatchEval));

			sb = new StringBuilder();
			
			if (lineNumbers || alternate) //we have to process the code line by line
			{
				if(!subCode)
					sb.Append("<div class=\"csharpcode\">\n");
				var reader = new StringReader(source);
				int i = 0;
				string spaces = "    ";
				int order;
				string line;
				while ((line = reader.ReadLine()) != null)
				{
					i++;
					if (alternate && ((i % 2) == 1))
					{
						sb.Append("<pre class=\"alt\">");
					}
					else
					{
						sb.Append("<pre>");
					}

					if(lineNumbers)
					{
						order = (int)Math.Log10(i);
						sb.Append("<span class=\"lnum\">" 
							+ spaces.Substring(0, 3 - order) + i.ToString() 
							+ ":  </span>");
					}
					
					if(line.Length == 0)
						sb.Append("&nbsp;");
					else
						sb.Append(line);
					sb.Append("</pre>\n");
				}
				reader.Close();
				if(!subCode)
					sb.Append("</div>");
			}
			else
			{
				if(!subCode)
					sb.Append("{{");
				sb.Insert(0, @"<font size=small color=black font-family=""Consolas, Courier New, Courier, Monospace"">");
				sb.Append(source.Replace("\n", "{br}\n"));
				sb.Append(@"</font>");
				if (!subCode)
					sb.Append("}}");
			}

			return sb.ToString();
		}

		private string NormalizeTabs(string source)
		{
			source = source.Replace("\t", "".PadRight(TabSize, ' '));
			var lines = source.Split('\n');
			var minSpacing = 100;
			foreach (var line in lines)
			{
				if (string.IsNullOrEmpty(line))
					continue;
				minSpacing = Math.Min(minSpacing, LeadingSpaces(line));
			}

			for (int i = 0; i < lines.Length; i++)
			{
				if (string.IsNullOrEmpty(lines[i]))
					continue;
				lines[i] = lines[i].Substring(minSpacing);
				if (!string.IsNullOrEmpty(lines[i]) && lines[i][0] == ' ')
				{
					var lead = LeadingSpaces(lines[i]);
					lines[i] = lines[i].Substring(0, lead).Replace(" ","&nbsp;") + lines[i].Substring(lead);
				}
			}

			source = string.Join("\n", lines);
			return source; //.Replace(" ", "&nbsp;");
		}

		private static int LeadingSpaces(string line)
		{
			var spacesBefore = 0;
			foreach (char t in line)
				if (t == ' ')
					spacesBefore++;
				else
					break;
			return spacesBefore;
		}

		protected virtual int TabSize
		{
			get { return 4; }
		}
	}
}
